<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\translation;

use app\adminapi\controller\Base;
use app\common\model\TranslationConfig as TranslationConfigModel;
use app\common\model\Language;

/**
 * 翻译配置管理控制器
 */
class Config extends Base
{
    /**
     * @notes 获取翻译配置列表
     * @auth true
     */
    public function getList()
    {
        $page      = inputs('page/d', 1);
        $limit     = inputs('limit/d', 20);
        $tableName = inputs('table_name/s', '');

        $where = [];
        if ($tableName) {
            $where[] = ['table_name', '=', $tableName];
        }

        $list = TranslationConfigModel::where($where)
            ->order('table_name', 'asc')
            ->order('field_name', 'asc')
            ->paginate([
                'list_rows' => $limit,
                'page'      => $page,
            ]);

        $this->success('', $list);
    }

    /**
     * @notes 获取配置详情
     * @auth true
     */
    public function getDetail()
    {
        $id     = inputs('id/d', 0);
        $config = TranslationConfigModel::find($id);

        if (!$config) {
            $this->error('配置不存在');
        }

        $this->success('', $config);
    }

    /**
     * @notes 添加翻译配置
     * @auth true
     */
    public function addConfig()
    {
        $data = [
            'table_name'       => inputs('table_name/s', ''),
            'field_name'       => inputs('field_name/s', ''),
            'is_enabled'       => inputs('is_enabled/d', 1),
            'auto_translate'   => inputs('auto_translate/d', 1),
            'target_languages' => inputs('target_languages/a', []),
        ];

        if (!$data['table_name'] || !$data['field_name']) {
            $this->error('参数不完整');
        }

        // 检查配置是否已存在
        $exists = TranslationConfigModel::where([
            'table_name' => $data['table_name'],
            'field_name' => $data['field_name']
        ])->count();

        if ($exists) {
            $this->error('该字段的翻译配置已存在');
        }

        $config = new TranslationConfigModel();
        $config->save($data);

        $this->success('添加成功');
    }

    /**
     * @notes 编辑翻译配置
     * @auth true
     */
    public function editConfig()
    {
        $id   = inputs('id/d', 0);
        $data = [
            'is_enabled'       => inputs('is_enabled/d', 1),
            'auto_translate'   => inputs('auto_translate/d', 1),
            'target_languages' => inputs('target_languages/a', []),
        ];

        $config = TranslationConfigModel::find($id);
        if (!$config) {
            $this->error('配置不存在');
        }

        $config->save($data);
        $this->success('编辑成功');
    }

    /**
     * @notes 删除翻译配置
     * @auth true
     */
    public function deleteConfig()
    {
        $id     = inputs('id/d', 0);
        $config = TranslationConfigModel::find($id);

        if (!$config) {
            $this->error('配置不存在');
        }

        $config->delete();
        $this->success('删除成功');
    }

    /**
     * @notes 启用/禁用配置
     * @auth true
     */
    public function toggleConfig()
    {
        $id     = inputs('id/d', 0);
        $config = TranslationConfigModel::find($id);

        if (!$config) {
            $this->error('配置不存在');
        }

        $config->toggleEnabled();
        $action = $config->is_enabled ? '启用' : '禁用';
        $this->success("{$action}成功");
    }

    /**
     * @notes 启用/禁用自动翻译
     * @auth true
     */
    public function toggleAutoTranslate()
    {
        $id     = inputs('id/d', 0);
        $config = TranslationConfigModel::find($id);

        if (!$config) {
            $this->error('配置不存在');
        }

        $config->toggleAutoTranslate();
        $action = $config->auto_translate ? '启用' : '禁用';
        $this->success("自动翻译{$action}成功");
    }

    /**
     * @notes 批量创建推荐配置
     * @auth true
     */
    public function createRecommendedConfigs()
    {
        $configs         = TranslationConfigModel::getRecommendedConfigs();
        $targetLanguages = Language::getEnabledLanguages()->column('code');

        // 移除默认语言
        $targetLanguages = array_filter($targetLanguages, function ($code) {
            return $code !== 'zh_CN';
        });

        $data = [];
        foreach ($configs as $config) {
            $data[] = [
                'table_name'       => $config['table_name'],
                'field_name'       => $config['field_name'],
                'is_enabled'       => 1,
                'auto_translate'   => 1,
                'target_languages' => $targetLanguages,
            ];
        }

        TranslationConfigModel::batchCreateConfigs($data);
        $this->success('推荐配置创建成功');
    }

    /**
     * @notes 获取推荐配置
     * @auth true
     */
    public function getRecommendedConfigs()
    {
        $configs = TranslationConfigModel::getRecommendedConfigs();
        $this->success('', $configs);
    }

    /**
     * @notes 获取配置统计
     * @auth true
     */
    public function getConfigStats()
    {
        $stats = TranslationConfigModel::getConfigStats();
        $this->success('', $stats);
    }

    /**
     * @notes 获取可翻译的表列表
     * @auth true
     */
    public function getTranslatableTables()
    {
        // 这里可以扫描数据库获取所有表，或者返回预定义的表列表
        $tables = [
            'goods'          => '商品',
            'goods_category' => '商品分类',
            'goods_spec'     => '商品规格',
            'goods_tag'      => '商品标签',
            'articles'       => '文章',
            'site_config'    => '网站配置',
            'pages'          => '页面',
            'menus'          => '菜单',
        ];

        $this->success('', $tables);
    }

    /**
     * todo
     * @notes 获取表的字段列表
     * @auth true
     */
    public function getTableFields()
    {
        $tableName = inputs('table_name/s', '');

        if (!$tableName) {
            $this->error('请指定表名');
        }

        // 这里可以通过数据库查询获取表字段，或者返回预定义的字段列表
        $fieldMap = [
            'goods'          => ['name', 'content', 'seo_title', 'seo_description', 'summary'],
            'goods_category' => ['name', 'description'],
            'goods_spec'     => ['name'],
            'goods_tag'      => ['name'],
            'articles'       => ['title', 'content', 'summary'],
            'site_config'    => ['site_name', 'site_description', 'site_keywords'],
        ];

        $fields = $fieldMap[$tableName] ?? [];
        $this->success('', $fields);
    }
}
